package org.xfy.order.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.xfy.base.util.AjaxResult;
import org.xfy.base.util.StrUtils;
import org.xfy.order.domain.Dto.AdoptOrderDto;
import org.xfy.order.domain.OrderAddress;
import org.xfy.order.domain.OrderAdopt;
import org.xfy.order.domain.UserAddress;
import org.xfy.order.mapper.OrderAddressMapper;
import org.xfy.order.mapper.OrderAdoptMapper;
import org.xfy.order.mapper.UserAddressMapper;
import org.xfy.order.service.IOrderAdoptService;
import org.xfy.base.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.xfy.org.domain.LoginData;
import org.xfy.org.domain.Logininfo;
import org.xfy.pet.domain.Pet;
import org.xfy.pet.mapper.PetMapper;
import org.xfy.sys.domain.User;
import org.xfy.sys.mapper.UserMapper;

import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class OrderAdoptServiceImpl extends BaseServiceImpl<OrderAdopt> implements IOrderAdoptService {
    @Autowired
    private UserAddressMapper userAddressMapper;
    @Autowired
    OrderAddressMapper orderAddressMapper;
    @Autowired
    private PetMapper petMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    @Transactional
    public AjaxResult submitOrder(AdoptOrderDto adoptOrderDto,LoginData loginData) {
        Pet pet = adoptOrderDto.getPet();
        //修改下架状态
        Pet one1 = petMapper.findOne(pet.getId());
        one1.setState(0);
        petMapper.update(one1);

        OrderAdopt orderAdopt = new OrderAdopt();
        orderAdopt.setDigest(pet.getName()+"的领养订单");
        String OrderSn=StrUtils.getRandomString(12);
        orderAdopt.setOrderSn(OrderSn);
        orderAdopt.setPaySn(StrUtils.getRandomString(12));
        orderAdopt.setState(1);
        orderAdopt.setPrice(adoptOrderDto.getPrice());
        long currentTime = System.currentTimeMillis() + 30 * 60 * 1000;
        orderAdopt.setLastPayTime(new Date(currentTime));
        orderAdopt.setPetId(pet.getId());
        //获取用户
        Logininfo logininfo = loginData.getLogininfo();
        User user = userMapper.findOneByLogininfo(logininfo.getId());
        orderAdopt.setUserId(user.getId());
        orderAdopt.setShopId(pet.getShopId());
        super.add(orderAdopt);

        //订单地址
        UserAddress one = userAddressMapper.findOne(adoptOrderDto.getAddressId());
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(one,orderAddress);
        orderAddress.setOrderSn(OrderSn);
        orderAddress.setOrderId(orderAdopt.getId());
        orderAddressMapper.add(orderAddress);
        return AjaxResult.me();
    }
}
